package com.friends.utils.file;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件base64加解密
 * MultipartFile 2 File
 * @Author Z-7
 * @Date 2022/11/23
 */
@Slf4j
@UtilityClass
public class FileTransitionUtil {
    private static final String SALT = "helloKitty";
    private static final String FILE_BASE_PATH = "D:/";

    private static String SUFFIX = ".%s";

    public static void main(String[] args) throws IOException {
        // String s = fileEncode(new File());
        // fileDecoder(s);
//        String string = "abcdef";
//        System.out.println(string.length());
//        for (int i = string.length(); i >= 0 ; i--) {
//            System.out.println(i + string.charAt(i));
//        }

        String encode = Base64.encode("%bb7tNai");
        System.out.println(encode);
    }

    /**
     * 将文件进行base64加密
     * @param file
     * @return
     * @throws IOException
     */
    public static String fileEncode(File file) throws IOException {
        //File file = new File("D:/sql.txt");
        SUFFIX = String.format(SUFFIX, FileUtil.getSuffix(file));
        return Base64.encode(file);
    }

    /**
     * 将文件的base64还原
     * @param code
     * @throws IOException
     */
    public static void fileDecoder(String code) throws IOException {
        File file = Base64.decodeToFile(code, new File(FILE_BASE_PATH + IdUtil.simpleUUID() + SUFFIX));
        System.out.println(file.getAbsolutePath());
    }

    /**
     * multipartFile  ->  file
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public static File multipartFile2File(MultipartFile multipartFile) throws IOException {
        File file = new File(FILE_BASE_PATH + multipartFile.getOriginalFilename());
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),file);
        return file;
    }

}
